﻿using com.kmer.ApiServer;
using com.kmer.ApiServer.Attributes;
using com.kmer.Attributes;
using com.kmer.db;
using com.kmer.Helper;
using EntityFramework.Extensions;
using kmer.Data;
using OrderAPI.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.kmer.Cache;

namespace OrderAPI
{
    [Description("定版,系列排行列表")]
    public class ChooseVersionHandler : BaseHandler
    {
        #region API
        [MustLogin]
        [Description("评分结果列表（按系列分组）")] //{"MasterID":38,"SerialName":"创意","ItemName":"","Sort":1,"Page":1,"Size":20}
        [ReturnType(typeof(PaperData<ChooseVersionDataList>))]
        public ApiResult GetList(
            [ParamDescription("订货会ID")]int MasterID,
            [ParamDescription("系列")]string SerialName,
            [ParamDescription("项目")]string ItemName = "",
            [ParamDescription("排序(1-从高到低,0-从低到高)")]int Sort = 1,
            [ParamDescription("页码")]int Page = 1,
            [ParamDescription("页数")]int Size = 20)
        {
            var dc = new km_platformEntities();
            var query = (from t in dc.t_order_styledetail
                         join b in dc.t_order_master
                         on t.MasterID equals b.MasterID
                         where t.MasterID == MasterID && t.SerialName == SerialName && t.CompanyID == this.CompanyID
                         select new
                         {
                             t.DetailID,
                             t.MasterID,
                             b.OrderName,
                             t.SerialNo,
                             t.DesignNo,
                             t.SerialName,
                             t.ItemName,
                             t.MaterialProperty,
                             t.RetailPrice,
                             AllPersonaCount = dc.t_order_userweight.Count(),
                             GradePersonaCount = dc.t_order_GradeResult_Mater.
                                                 Where(g => g.MasterID == t.MasterID && g.SerialNo == t.SerialNo).
                                                 GroupBy(gg => gg.UserID).Count(),
                             ChooseFlag = dc.t_order_ChooseVersion.FirstOrDefault(c => c.MasterID == t.MasterID && c.SerialNo == t.SerialNo)
                         });
            if (!string.IsNullOrWhiteSpace(ItemName))
                query = query.Where(t => t.ItemName == ItemName);
            //TODO:先排序后分页
            var list = query.OrderByDescending(t => t.DetailID).ToList()
               .Select(o => new OrderMaster.ChooseVersionData
               {
                   DetailID = o.DetailID,
                   MasterID = o.MasterID,
                   SerialNo = o.SerialNo,
                   DesignNo = o.DesignNo,
                   SerialName = o.SerialName,
                   ItemName = o.ItemName,
                   MaterialProperty = o.MaterialProperty,
                   RetailPrice = o.RetailPrice,
                   ImgUrl = o.SerialNo == null ? "" : Request.GetOSSImageUrl(o.SerialNo, o.OrderName, 1),
                   IntegrateScore = Math.Round(CaclIntegrateScore(dc, o.MasterID, o.SerialNo), 1), //cyl:2017-12-4改：格式小数点
                    AllPersonaCount = o.AllPersonaCount,
                   ChooseFlag = o.ChooseFlag == null ? false : o.ChooseFlag.ChooseFlag,
                   GradePersonaCount = o.GradePersonaCount
               }).ToList();
            list = Sort == 1 ? list.OrderByDescending(t => t.IntegrateScore).ToList()
               : list.OrderBy(t => t.IntegrateScore).ToList();

            var result = PaperData<OrderMaster.ChooseVersionData>.Create(list.Count(), Size, Page);
            result.Items = list.Skip(result.Skip)
                .Take(result.Limt).ToList();

            var model = new ChooseVersionDataList();
            model.PageData = result;
            model.CountNum = GetCountNum(MasterID, SerialName, ItemName);
            return Success(model);
        }


        /// writer：ljj
        /// date：2018-03-20
        [MustLogin]
        [Description("评分结果列表（按系列分组）")] //{"MasterID":38,"SerialName":"创意","ItemName":"","Sort":1,"Page":1,"Size":20}
        [ReturnType(typeof(PaperData<OrderMaster.OrderStyleDetailDataV2>))]
        public ApiResult GetListV2([ParamDescription("订货会ID")] int MasterID, [ParamDescription("系列")] string SerialName,
            [ParamDescription("项目")] string ItemName = "", [ParamDescription("排序(1-从高到低,0-从低到高)")] int Sort = 1,
            [ParamDescription("页码")] int Page = 1, [ParamDescription("页数")] int Size = 20)
        {
            try
            {
                var dc = new km_platformEntities();
                var companyID = "KM";
                var query = (from sd in dc.t_order_styledetail
                             join m in dc.t_order_master
                             on new { sd.MasterID, sd.CompanyID, sd.ExtrSource } equals new { m.MasterID, m.CompanyID, m.ExtrSource }
                             join w in dc.t_order_userweight
                             on new { sd.CompanyID, sd.ExtrSource } equals new { w.CompanyID, w.ExtrSource }
                             where sd.MasterID == MasterID && sd.SerialName == SerialName &&
                                   (string.IsNullOrEmpty(ItemName) || sd.ItemName == ItemName) &&
                                   sd.CompanyID == companyID &&
                                   (w.Grade.HasValue && w.Grade == true)
                             join temp1 in (from rm in dc.t_order_GradeResult_Mater
                                            join rd in dc.t_order_GradeResult_Detail
                                            on rm.ResultID equals rd.ResultID
                                            select new
                                            {
                                                rm,
                                                rd
                                            })
                             on new { sd.MasterID, sd.CompanyID, sd.ExtrSource, w.UserID, sd.SerialNo } equals new
                             {
                                 temp1.rm.MasterID,
                                 temp1.rm.CompanyID,
                                 temp1.rm.ExtrSource,
                                 temp1.rm.UserID,
                                 temp1.rm.SerialNo
                             }
                             into temp2
                             from t2 in temp2.DefaultIfEmpty()
                             join l in dc.t_order_Fashion_level
                             on new { sd.MasterID, sd.CompanyID, sd.ExtrSource, sd.SerialNo } equals new
                             {
                                 l.MasterID,
                                 l.CompanyID,
                                 l.ExtrSource,
                                 l.SerialNo
                             }
                             into temp3
                             from t3 in temp3.DefaultIfEmpty()
                             group new
                             {
                                 w,
                                 Count = t2 == null ? 0 : 1,
                                 AStoreRating = w.ScoreRate * (t2 == null ? 0 : t2.rd.AStoreRating),
                                 BStoreRating = w.ScoreRate * (t2 == null ? 0 : t2.rd.BStoreRating),
                                 StyleRating = w.ScoreRate * (t2 == null ? 0 : t2.rd.StyleRating),
                                 sd,
                                 m
                             } by new
                             {
                                 sd.SerialNo,
                                 sd.DesignNo,
                                 AStoreLevel = t3 == null ? "" : t3.AStoreLevel,
                                 BStoreLevel = t3 == null ? "" : t3.BStoreLevel,
                             }
                    into tt
                             select tt);
                query = Sort == 1
                    ? query.OrderByDescending(d => d.Sum(r => r.Count) == 0
                        ? 0
                        : (double)d.Sum(r => r.AStoreRating) / (d.Sum(r => r.Count) * 1.0)).ThenBy(d => d.Key.SerialNo)
                    : query.OrderBy(d => d.Sum(r => r.Count) == 0
                            ? 0
                            : (double)d.Sum(r => r.AStoreRating) / (d.Sum(r => r.Count) * 1.0))
                        .ThenBy(d => d.Key.SerialNo);
                var result = PaperData<OrderMaster.OrderStyleDetailDataV2>.Create(query.Count(), Size, Page);
                var list = query.Skip(result.Skip)
                    .Take(result.Limt).ToList().Select(d => new OrderMaster.OrderStyleDetailDataV2
                    {
                        DetailID = d.FirstOrDefault().sd.DetailID,
                        MasterID = d.FirstOrDefault().sd.MasterID,
                        SerialNo = d.Key.SerialNo,
                        DesignNo = d.Key.DesignNo,
                        SerialName = d.FirstOrDefault().sd.SerialName,
                        ItemName = d.FirstOrDefault().sd.ItemName,
                        MaterialProperty = d.FirstOrDefault().sd.MaterialProperty,
                        RetailPrice = d.FirstOrDefault().sd.RetailPrice,
                        ImgUrl = d.Key.SerialNo == null
                            ? ""
                            : Request.GetOSSImageUrlV2(d.FirstOrDefault().sd.MasterID, d.Key.SerialNo),
                        AllPersonaCount = d.Count(),
                        GradePersonaCount = d.Sum(r => r.Count),
                        AStoreRating = d.Sum(r => r.Count) == 0
                            ? 0
                            : (double)d.Sum(r => r.AStoreRating) / (d.Sum(r => r.Count) * 1.0),
                        BStoreRating = d.Sum(r => r.Count) == 0
                            ? 0
                            : (double)d.Sum(r => r.BStoreRating) / (d.Sum(r => r.Count) * 1.0),
                        StyleRating = d.Sum(r => r.Count) == 0
                            ? 0
                            : (double)d.Sum(r => r.StyleRating) / (d.Sum(r => r.Count) * 1.0),
                        AStoreLevel = d.Key.AStoreLevel,
                        BStoreLevel = d.Key.BStoreLevel
                    }).ToList();
                list.ForEach(d =>
                {
                    d.AStoreLevel = string.IsNullOrEmpty(d.AStoreLevel)
                        ? (d.AStoreRating > 7 ? "A" : (d.AStoreRating < 4.5 ? "C" : "B"))
                        : d.AStoreLevel;
                    d.BStoreLevel = string.IsNullOrEmpty(d.BStoreLevel)
                        ? (d.BStoreRating > 7 ? "A" : (d.BStoreRating < 4.5 ? "C" : "B"))
                        : d.BStoreLevel;
                });
                result.Items = list;
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }


        /// writer：ljj
        /// date：2018-03-28
        [MustLogin]
        [Description("评分结果列表（按系列分组）")] //{"MasterID":38,"SerialName":"创意","ItemName":"","Sort":1,"Page":1,"Size":20}
        [ReturnType(typeof(PaperData<OrderMaster.OrderStyleDetailDataV2>))]
        public ApiResult GetListV3([ParamDescription("订货会ID")] int MasterID, [ParamDescription("系列")] string SerialName,
            [ParamDescription("项目")] string ItemName = "", [ParamDescription("排序(1-从高到低,0-从低到高)")] int Sort = 1,
            [ParamDescription("页码")] int Page = 1, [ParamDescription("页数")] int Size = 20)
        {
            try
            {
                var sql = $@"
EXEC	[km_platform].[dbo].[sp_order_Result]
		@CompanyID = 'KM',
		@ExtrSource = 'KM',
		@MasterID = {MasterID},
		@SerialName = '{SerialName}',
		@ItemName = '{ItemName}',
		@Sort = {Sort}";
                var dc = new km_platformEntities();
                var query = dc.Database.SqlQuery<OrderMaster.OrderStyleDetailDataV2>(sql);
                var result = PaperData<OrderMaster.OrderStyleDetailDataV2>.Create(query.Count(), Size, Page);
                result.Items = query.Skip(result.Skip)
                    .Take(result.Limt).ToList();
                return Success(result);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        [MustLogin]
        [Description("定版")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Choose([ParamDescription("订货会ID")]int MasterID,
            [ParamDescription("流水号")]string SerialNo,
            [ParamDescription("综合得分")]decimal IntegrateScore,
            [ParamDescription("定版(1-定版,0-取消定版)")]bool ChooseFlag = true
            )
        {
            //TODO:定版保存数据逻辑
            //ChooseFlag==false时，当前订货会的流水号在定版表中存在则删除，
            //ChooseFlag==true,则增加记录
            var dc = new km_platformEntities();
            var data = dc.t_order_ChooseVersion.FirstOrDefault(t => t.MasterID == MasterID
            && t.SerialNo == SerialNo && t.CompanyID == this.CompanyID);
            if (data == null && ChooseFlag)
            {
                var add = new t_order_ChooseVersion
                {
                    ChooseFlag = ChooseFlag,
                    CompanyID = this.CompanyID,
                    ExtrSource = this.CompanyID,
                    GradeTime = DateTime.Now,
                    MasterID = MasterID,
                    IntegrateScore = IntegrateScore,
                    SerialNo = SerialNo,
                    UserID = this.CusID
                };
                dc.t_order_ChooseVersion.Add(add);
            }
            else
            {
                dc.t_order_ChooseVersion.Where(t => t.MasterID == MasterID
             && t.SerialNo == SerialNo && t.CompanyID == CompanyID).Delete();
            }
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }


        /// writer：ljj
        /// date：2018-03-20
        [MustLogin]
        [JsonType]
        [Description("保存评分结果")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Save([ParamDescription("评分结果")] OrderMaster.OrderFashionLevelSaveModel param)
        {
            try
            {
                if (param == null) return Error("参数对象为空");
                var user = this.CacheLoginUserData();
                if (!(user.Management.HasValue || user.Management.Value)) return Error("该用户没有权限!");
                if (param.list != null)
                {
                    var dc = new km_platformEntities();
                    foreach (var item in param.list)
                    {

                        var query = dc.t_order_Fashion_level.FirstOrDefault(
                            d => d.MasterID == item.MasterID && d.SerialNo == item.SerialNo);
                        if (query == null)
                        {
                            dc.t_order_Fashion_level.Add(new t_order_Fashion_level
                            {
                                UserID = this.CusID,
                                CompanyID = this.CompanyID,
                                ExtrSource = this.CompanyID,
                                AStoreLevel = item.AStoreLevel,
                                BStoreLevel = item.BStoreLevel,
                                MasterID = item.MasterID,
                                SerialNo = item.SerialNo,
                                UpdateTime = DateTime.Now,
                            });
                        }
                        else
                        {
                            query.UserID = this.CusID;
                            query.CompanyID = this.CompanyID;
                            query.ExtrSource = this.CompanyID;
                            query.AStoreLevel = item.AStoreLevel;
                            query.BStoreLevel = item.BStoreLevel;
                            query.UpdateTime = DateTime.Now;
                        }
                    }
                    dc.SaveChanges();
                }
                return Success(0);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }

        #endregion

        #region 方法
        //获取订版相关统计数据
        public OrderMaster.CountVersionData GetCountNum(int MasterID, string SerialName, string ItemName)
        {
            var model = new OrderMaster.CountVersionData();
            try
            {
                var dc = new km_platformEntities();
                //获取系列项目SKC数
                var query3 = dc.t_order_SKCRequire.Where(t => t.MasterID == MasterID && t.SerialName == SerialName && t.CompanyID == this.CompanyID);
                if (!string.IsNullOrWhiteSpace(ItemName))
                {
                    query3 = query3.Where(t => t.ItemName == ItemName);
                }
                model.SerialItemSKC = query3 == null ? 0 : query3.Sum(d => d.SKCQty);

                //获取已选数
                var query4 = (from o in dc.t_order_styledetail
                              join d in dc.t_order_ChooseVersion
                              on o.SerialNo equals d.SerialNo
                              where o.MasterID == MasterID && o.SerialName == SerialName && d.MasterID == MasterID && o.CompanyID == this.CompanyID && d.CompanyID == this.CompanyID
                              select new
                              {
                                  MasterID = o.MasterID,
                                  ItemName = o.ItemName
                              }).ToList();
                if (!string.IsNullOrWhiteSpace(ItemName))
                {
                    query4 = (from a in query4 where a.ItemName == ItemName select a).ToList();
                }
                model.SelectedNum = query4 == null ? 0 : query4.Count;

                //系列
                model.SerialName = SerialName;
            }
            catch (Exception ex)
            {
                model.SerialItemSKC = 0;
                model.SelectedNum = 0;
                model.SerialName = SerialName;
            }
            return model;
        }

        /// <summary>
        /// 计算单流水号综合得分
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="masterId"></param>
        /// <param name="SerialNo"></param>
        /// <returns></returns>
        decimal CaclIntegrateScore(km_platformEntities dc, int masterId, string SerialNo)
        {
            //定版表中无记录则计算综合得分，有则直接返回
            if (dc == null) dc = new km_platformEntities();
            var data = dc.t_order_ChooseVersion.FirstOrDefault(t => t.MasterID == masterId && t.SerialNo == SerialNo);
            if (data == null)
                return (from m in dc.t_order_GradeResult_Mater
                        where m.MasterID == masterId && m.SerialNo == SerialNo
                        select m.ResultID).Any() == false ? 0 :
                        (from m in dc.t_order_GradeResult_Mater
                         where m.MasterID == masterId && m.SerialNo == SerialNo
                         select new
                         {
                             m.MasterID,
                             m.SerialNo,
                             m.UserID,
                             m.PersonalScore,
                             PersonalRate = (from user in dc.t_order_userweight
                                             where user.UserID == m.UserID
                                             select user.ScoreRate).FirstOrDefault(),
                             AllRate = (from all in dc.t_order_userweight
                                        where
                                          (from md in dc.t_order_GradeResult_Mater
                                           where md.MasterID == masterId && md.SerialNo == SerialNo
                                           select md.UserID).Contains(all.UserID)
                                        select all.ScoreRate).Sum()
                         }).Select(o => o.PersonalScore * (o.PersonalRate / o.AllRate)).Sum();
            return data.IntegrateScore;
        }

        #endregion

        #region 实体类
        [Description("定版列表数据实体类")]
        public class ChooseVersionDataList
        {
            [ParamDescription("定版分页数据")]
            public PaperData<OrderMaster.ChooseVersionData> PageData { get; set; }
            [ParamDescription("订货会内的相关统计数据")]
            public OrderMaster.CountVersionData CountNum { get; set; }
        }

        #endregion

    }
}
